package delete;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreFailureException;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class DeleteMediaServlet extends HttpServlet {
	private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, BlobstoreFailureException {
		Key entityKey = KeyFactory.stringToKey(req.getParameter("entityKey"));
		Entity audioInfo;
		try {
			audioInfo = datastore.get(entityKey);
			BlobKey blobKey = (BlobKey) audioInfo.getProperty("blobKey");
			deleteMediaFile(audioInfo, blobKey);
		} catch (EntityNotFoundException e) {
			// delete failed, redirect to a different page
		} catch (BlobstoreFailureException e1) {
			resp.sendRedirect(req.getHeader("referer"));
		}
		
		// redirect to a confirmation page
		resp.sendRedirect(req.getHeader("referer"));
	}
	
	public static void deleteMediaFile(Entity mediaInfo, BlobKey blobKey) {
		// delete the object from the blobstore
		blobstoreService.delete(blobKey);
		// delete the entity in the datastore
		datastore.delete(mediaInfo.getKey());
	}
}
